﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;
        private int flag_price = 0;             //- Флаг цены, 0 - закупка с НДС, 1 - розница
        private DateTime date_b;                //- Начало периода отчёта
        private DateTime date_e;                //- Окончание периода отчёта
        private int flag = 0;                   //- 0 - без аптек и товаров, 1 - аптеки, 2 - товары, 3 - аптеки и товары
        
        private DataTable dt_drug_tmp;                          //- Выбранные товары
        private DataTable dt_brand = new DataTable();           //- Брэнды
        private DataTable dt_drugs;                             //- Все товары
        private DataTable dt_pharm;                             //- Фильтр по аптекам
        private DataTable dt_ph;                                //- Для передачи в фильтр
        private DataTable dt_dr;                                //- Для передачи в фильтр
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            listBox2.Items.Add("(Все товары)");
            listBox1.Items.Add("(Все аптеки)");
            this.Text = "Разделение потоков - оборачиваемость";

            //- Параметры по умолчанию
            dateTimePicker1.Value = DateTime.Now.AddDays(-15).Date;
            dateTimePicker2.Value = DateTime.Now.AddDays(-1).Date;
            date_b = dateTimePicker1.Value;
            date_e = dateTimePicker2.Value;

            checkBox1.Checked = false;
            checkBox2.Checked = false;
            flag = 0;
            radioButton1.Checked = true;
            flag_price = 0;

        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null; 
            dt_rep = null;
            dt_rep = new DataTable();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            dt_dr = new DataTable();
            dt_ph = new DataTable();
            dt_dr.Columns.Add();
            dt_ph.Columns.Add();

            if (dt_drug_tmp != null)
            {
                foreach (DataRow dr in dt_drug_tmp.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) dt_dr.Rows.Add(dr["Код"]);
                }
            }
            if (dt_pharm != null)
            {
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) dt_ph.Rows.Add(dr["Код"]);
                }
            }

            try
            {
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[6];
                par[0].name = "@flag";
                par[0].value = flag;
                par[1].name = "@flag_price";
                par[1].value = flag_price;
                par[2].name = "@date_b";
                par[2].value = date_b;
                par[3].name = "@date_e";
                par[3].value = @date_e;
                par[4].name = "@pharm";
                par[4].value = dt_ph;
                par[5].name = "@drugs";
                par[5].value = dt_dr;
 
                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "[pas_CommDep_Auction_turnover]", 300, par);

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "csv-file";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //- Фильтр по товарам
            DrugsFilter.DrugsFilter f2 = new DrugsFilter.DrugsFilter();
            DrugsFilter.DrugsFilter.StorProcParam[] spp = new DrugsFilter.DrugsFilter.StorProcParam[1];

            spp[0] = f2.StorProcParamIns("@arch", SqlDbType.VarChar, 20, "jhjhjh");

            SqlCommand myCommand = new SqlCommand();
            myCommand = f2.StorProc(myCommand, conn, "pas_AllDrugsSel", spp);

            if (dt_drugs == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drugs = new DataTable();
                    dt_drugs.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drugs.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    dt_brand = new DataTable();
                    dt_brand.Load(GetBrandTree(conn));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
                f2.rb = true;
            }
            if (dt_drug_tmp == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drug_tmp = new DataTable();
                    dt_drug_tmp.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drug_tmp.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
            }
            f2.sqlconn = conn;
            f2.namechcol = namechcol;
            f2.dt_drug = dt_drugs;
            f2.dt_drug_tmp = dt_drug_tmp;
            if (dt_drug_tmp.Rows.Count == 0)
                f2.dataGridView1.DataSource = f2.dt_drug.DefaultView;
            else
                f2.dataGridView1.DataSource = f2.dt_drug_tmp.DefaultView;
            f2.dt_br = dt_brand;
            f2.ShowDialog();
            listBox2.Items.Clear();
            foreach (DataRow dr in dt_drug_tmp.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true && dr.RowState != DataRowState.Deleted) listBox2.Items.Add(dr["Товар"]);
            }
            if (listBox2.Items.Count == 0) listBox2.Items.Add("(Все товары)");
            f2.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //- Фильтр по аптекам
            try
            {
                PharmFilter.PharmFilter f3 = new PharmFilter.PharmFilter();

                if (dt_pharm == null)
                {
                    SqlCommand myCommand = conn.CreateCommand();
                    myCommand.CommandType = CommandType.StoredProcedure;
                    myCommand.CommandText = @"pas_PharmSel";
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_pharm = new DataTable();
                    dt_pharm.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_pharm.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    conn.Close();
                }
                f3.namechcol = namechcol;
                f3.Text = "Фильтр по аптекам";
                f3.sortcoumn = "Аптека";
                f3.dataGridView1.DataSource = dt_pharm.DefaultView;
                f3.ShowDialog();
                listBox1.Items.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) listBox1.Items.Add(dr[f3.sortcoumn]);
                }
                if (listBox1.Items.Count == 0) listBox1.Items.Add("(Все аптеки)");
                f3.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true && checkBox2.Checked == false)
            {
                flag = 1;
            }
            else if (checkBox1.Checked == true && checkBox2.Checked == true)
            {
                flag = 3;
            }
            else if (checkBox1.Checked == false && checkBox2.Checked == false)
            {
                flag = 0;
            }
            else if (checkBox1.Checked == false && checkBox2.Checked == true)
            {
                flag = 2;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true && checkBox2.Checked == false)
            {
                flag = 1;
            }
            else if (checkBox1.Checked == true && checkBox2.Checked == true)
            {
                flag = 3;
            }
            else if (checkBox1.Checked == false && checkBox2.Checked == false)
            {
                flag = 0;
            }
            else if (checkBox1.Checked == false && checkBox2.Checked == true)
            {
                flag = 2;
            }
        } 

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            //- Закупочная цена с НДС
            flag_price = 0;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            //- Розничная цена
            flag_price = 1;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            //- Начало даты отчёта
            date_b = dateTimePicker1.Value;
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            //- Окончание даты отчёта
            date_e = dateTimePicker2.Value;
        }

        private SqlDataReader GetBrandTree(SqlConnection sqlcon)
        {
            SqlCommand com = sqlcon.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"pas_BrandTreeSel";

            return com.ExecuteReader();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //- Экспорт в Excel

        }

    }
}
